package com.color.admin.common.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.color.admin.common.core.result.ResultCode;
import com.color.admin.common.core.result.ResultData;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * @author HaiQiu
 * @date 2022/2/21
 * 认证失败处理
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();

        printWriter.write(JSONObject.toJSONString(ResultData.fail(ResultCode.NOT_LOGIN.getCode(),
                ResultCode.NOT_LOGIN.getMsg())));

        printWriter.flush();
    }
}
